package cn.micai.base.lambda;

import java.io.LineNumberReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述：Java 8 – Convert List to Map
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/21 19:28
 */
public class ListToMapExample {

    public static void main(String [] args) {

        // 1.List to Map - Collectors.toMap()

        List<Hosting> hostings = new ArrayList<>();
        hostings.add(new Hosting(1, "liquidweb.com", 80000));
        hostings.add(new Hosting(2, "linode.com", 90000));
        hostings.add(new Hosting(3, "digitalocean.com", 120000));
        hostings.add(new Hosting(4, "aws.amazon.com", 200000));
        hostings.add(new Hosting(5, "mkyong.com", 1));

        hostings.add(new Hosting(6, "linode.com", 100000)); // new line

        // key = id, value -name
        Map<Integer, String> result1 = hostings.stream()
                .collect(Collectors.toMap(Hosting::getId, Hosting::getName));
        System.out.println("Result 1: " + result1);

        // key = name, vaule - websites
        Map<String, Long> result2 = hostings.stream()
                .collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites,(oleValue,newValue)->oleValue));
        System.out.println("Result 2: " + result2);

        // Same with result1, just different syntax
        // key = id, value = name
        Map<Integer, String> result3 = hostings.stream()
                .collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));
        System.out.println("Result 3: " + result3);


        // 2.List to Map - Duplicated key!

        // key = name, value = websites, but the key 'linode' is duplicated!?
        Map<String, Long> result4 = hostings.stream()
                .collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites,(oldValue, newValue)->newValue));
        System.out.println("Result 4: " + result4);

        // 3.List to Map – Sort & Collect
        LinkedHashMap<String, Long> result5 = hostings.stream()
                .sorted(Comparator.comparingLong(Hosting::getWebsites).reversed())
                .collect(Collectors.toMap(
                        Hosting::getName, Hosting::getWebsites, // key = name, value = websites
                        (oldValue, newValue) -> oldValue,       // if same key, take the old key
                        LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                ));
        System.out.println("Result 5: " + result5);

    }
}
